package net.ustc.javamemcached.memorystore;

import java.util.Map;
import java.util.Set;

import org.jboss.netty.buffer.ChannelBuffer;

import net.ustc.javamemcached.Key;
import net.ustc.javamemcached.util.OpenBitSet;

public class MemoryLocation {
	/** used to find idle blocks */
	private OpenBitSet bitSet;
	/** save the location for keys */
	private Map<Key, Integer> keyValueLocation;

	/**
	 * 
	 * @param size
	 *            bit number, or block number of a bucket. Because every bit
	 *            represents one block in a bucket.
	 */
	public MemoryLocation(long size) {
		bitSet = new OpenBitSet(size);
	}

	/**
	 * find the index of the beginning idle block, the following desiredBlockNum
	 * blocks are idle.
	 * 
	 * @param key
	 * @return the index of the beginning idle block, -1 means no space to save k/v
	 */
	public int findIdleLocation(int desiredBlockNum) {
		return bitSet.mark(desiredBlockNum);
	}

	public int findKeyValueLocation(Key key) {
		return keyValueLocation.get(key);
	}

	public void saveKeyValueLocation(Key key, int indexBlock) {
		keyValueLocation.put(key, indexBlock);
	}

	public boolean isKeyExist(Key key) {
		return keyValueLocation.containsKey(key);
	}

	public void reset(long begin, long length) {
		bitSet.clear(begin, begin + length);
	}

	public void removeKeyValue(Key key) {
		keyValueLocation.remove(key);
	}
	
	public Set<Key> getKeySet(){
		return keyValueLocation.keySet();
	}

	/** Close the store, destroying all data and closing the backing file */
	public void close() {
		// say goodbye to the region list
		bitSet = new OpenBitSet(bitSet.size());
		keyValueLocation.clear();
	}
}
